package com.stadium.controller;

import com.stadium.common.BaseResponse;
import com.stadium.common.utils.FileUtils;
import com.stadium.dto.FileDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/uploadFile")
@Api(tags =  "文件管理")
public class UploadFileCL {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 上传文件
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/v1/saveUploadFile")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ApiImplicitParams({@ApiImplicitParam(name="multipartFile",value="上传的文件",required = true),@ApiImplicitParam(name="serviceName",value="服务名（文件夹名称）",required = true)})
    public BaseResponse<FileDto> uploadFile(@RequestParam(value = "multipartFile",required = true) MultipartFile multipartFile,
                                   @RequestParam(value = "serviceName",required = true) String serviceName) {
        try {
            FileDto fileDto = FileUtils.uploadFile(multipartFile, serviceName);
            return BaseResponse.ok(fileDto);
        } catch (Exception e) {
            logger.error("上传文件失败！", e);
            return BaseResponse.error();
        }
    }

    @PostMapping("/v1/delFile")
    @ApiOperation(value = "删除文件", notes = "删除文件")
    @ApiImplicitParams({@ApiImplicitParam(name="filePath",value="要删除的文件地址",required = true)})
    public BaseResponse delFile(@RequestParam(value = "filePath",required = true) String filePath) {
        try {
            FileUtils.delFile(filePath);
            return BaseResponse.ok();
        }catch (Exception e){
            logger.error("删除文件失败！", e);
            return BaseResponse.error();
        }
    }

    @PostMapping("/v1/delFiles")
    @ApiOperation(value = "批量删除文件", notes = "删除文件")
    @ApiImplicitParams({@ApiImplicitParam(name="filePath",value="要删除的文件地址",required = true)})
    public BaseResponse delFiles(@RequestParam(value = "filePath",required = true) List<String> filePaths) {
        try {
            for (String filePath:filePaths){
                FileUtils.delFile(filePath);
            }
            return BaseResponse.ok();
        }catch (Exception e){
            logger.error("删除文件失败！", e);
            return BaseResponse.error();
        }
    }
}
